﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Styx.Plugins;
using System.Threading;
using System.Globalization;
using Styx.Common;
using System.Diagnostics;
using Styx.WoWInternals.WoWObjects;
using Styx;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media;
using Styx.CommonBot;
using Styx.Common.Helpers;
using Styx.WoWInternals;

namespace ShutUp
{
    public class ShutUp : HBPlugin
    {
        #region Nothing to see here!

        public override string Author { get { return "BarryDurex"; } }
        public override Version Version { get { return new Version(2, 0, 101); } }
        public override string Name { get { return "[ShutUp]"; } }
        public override string ButtonText { get { return "[ShutUp] Settings"; } }
        public override bool WantButton { get { return true; } }

        
        public Stopwatch loopTimer = new Stopwatch();
        private readonly WaitTimer _updateList = new WaitTimer(TimeSpan.FromMinutes(2));
        private static LocalPlayer Me { get { return StyxWoW.Me; } }
        public string ShutUpLogLocation = (Application.StartupPath + "\\Plugins\\ShutUp\\Logs\\ShutUp_" + Me.Name + ".txt");
        public string Forumlink = "";
        private Thread newThread;
        
        public void dlog(string message, params object[] args)
        { Logging.Write(Colors.Red, DateTime.Now.ToShortTimeString() + " - " + Name + ": " + message, args); }

        public void slog(Color color, string message, params object[] args)
        { Logging.Write(color, Name + ": " + message, args); }

        public void slog(string message, params object[] args)
        { Logging.Write(Colors.Orchid, Name + ": " + message, args); }

        #endregion

        #region on button press
        public override void OnButtonPress()
        {
            var _configForm = new SettingsForm();
            _configForm.ShowDialog();
        }
        #endregion

        public override void Initialize()
        {
            NotifyIconHelper.Initialize();
            //if (!NotifyIconHelper.NotifyIcn.Visible)
            //{ NotifyIconHelper.NotifyIcn.Visible = true; NotifyIconHelper.NotifyIcn.ShowBalloonTip(3500, "[ShutUp]", "You will find [ShutUp] here.", ToolTipIcon.Info); }

            FriendsList.Update();
            _updateList.Reset();

            #region File.Create(ShutUpLogLocation)
            if (!File.Exists(ShutUpLogLocation))
            {
                try
                {
                    File.Create(ShutUpLogLocation);
                }
                catch (Exception ex)
                {
                    slog(Colors.Red, "can not creat logfile");
                    slog(Colors.Red, "##################");
                    slog(Colors.Red, "{0}", ex);
                }
            }
            #endregion

            BotEvents.OnBotStop += stopBot;
            BotEvents.OnBotStart += startBot;


            if (ShutUpGlobalSettings.Instance.UpdateCheck && (newThread == null || !newThread.IsAlive))
            {
                TimeSpan ts = (DateTime.Now - ShutUpGlobalSettings.Instance.UpdateCheck_last);
                if (ts.TotalDays >= 1)
                {
                    newThread = new Thread(updateCheck) { IsBackground = true };
                    newThread.Start();
                }
            }
            dlog("- Initialized");
        }

        private void startBot(EventArgs args)
        {
            dlog("- startBot");
            loopTimer.Stop();
            Chat.Whisper += ChatHelper.newChat_Whisper;
            Chat.Party += ChatHelper.newChat_Party;
            Chat.PartyLeader += ChatHelper.newChat_Party;
            Chat.Guild += ChatHelper.newChat_Guild;
            Chat.Say += ChatHelper.newChat_Say;
            Chat.Yell += ChatHelper.newChat_Yell;
            Chat.Battleground += ChatHelper.newChat_Battleground;
            //TODO Chat.Officer += 
            Lua.Events.AttachEvent("CHAT_MSG_BN_WHISPER", ChatHelper.newChat_BNWhisper);

            //NotifyIconHelper.Initialize();
            if (!NotifyIconHelper.NotifyIcn.Visible)
            { NotifyIconHelper.NotifyIcn.Visible = true; NotifyIconHelper.NotifyIcn.ShowBalloonTip(3500, "[ShutUp]", "You will find [ShutUp] here.", ToolTipIcon.Info); }
        }

        private void stopBot(EventArgs args)
        {
            dlog("- stopBot");
            Chat.Whisper -= new Chat.ChatMessageHandlerEx<Chat.ChatWhisperEventArgs>(ChatHelper.newChat_Whisper);
            Chat.Party -= new Chat.ChatMessageHandlerEx<Chat.ChatLanguageSpecificEventArgs>(ChatHelper.newChat_Party);
            Chat.PartyLeader -= new Chat.ChatMessageHandlerEx<Chat.ChatLanguageSpecificEventArgs>(ChatHelper.newChat_Party);
            Chat.Say -= new Chat.ChatMessageHandlerEx<Chat.ChatLanguageSpecificEventArgs>(ChatHelper.newChat_Say);
            Chat.Guild -= new Chat.ChatMessageHandlerEx<Chat.ChatGuildEventArgs>(ChatHelper.newChat_Guild);
            Chat.Yell -= new Chat.ChatMessageHandlerEx<Chat.ChatLanguageSpecificEventArgs>(ChatHelper.newChat_Yell);
            Chat.Battleground -= new Chat.ChatMessageHandlerEx<Chat.ChatLanguageSpecificEventArgs>(ChatHelper.newChat_Battleground);
            Lua.Events.DetachEvent("CHAT_MSG_BN_WHISPER", ChatHelper.newChat_BNWhisper);
        }

        public override void Dispose()
        {
            try
            {
                //System.Media.SystemSounds.Asterisk.Play();
                newThread.Abort();
                FriendsList.newThread.Abort();
                if (ChatHelper._timer.Enabled)
                    ChatHelper._timer.Stop();
                NotifyIconHelper.NotifyIcn.Dispose();
            }
            catch (Exception ex) { }  
            dlog("- Dispose");          
        }

        public override void Pulse()
        {
            #region update friedslists
            if (!Me.Combat && _updateList.IsFinished)
            { _updateList.Reset(); FriendsList.Update(); }
            #endregion

            #region sound loop
            if (loopTimer.IsRunning && loopTimer.ElapsedMilliseconds > (ShutUpSettings.Instance.SoundLoopEvery * 1000))
            {
                dlog("sound loop \n\nloop: {0}", ChatHelper.loop);
                loopTimer.Reset(); loopTimer.Start();
                ChatHelper.loop++;
                ChatHelper.PlaySound(ChatHelper.soundLoopStatus);

                if (ChatHelper.loop == ShutUpSettings.Instance.SoundLoop) { ChatHelper.loop = 0; loopTimer.Stop(); }
            }
            #endregion
        }

        private void updateCheck()
        {
            System.Net.WebClient wClient = new System.Net.WebClient();
            string strSource = wClient.DownloadString("http://shutup.googlecode.com/svn/trunk/version/version.txt");
            Version _v = new Version(strSource);

            if (Version < _v)
            {
                string _msg = string.Format("a new version is available! \n Version: {0} \nDo you want to visit the forum now? {0}", strSource);

                if (MessageBox.Show(_msg, "new Version", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    System.Diagnostics.Process.Start(Forumlink);
            }

            ShutUpGlobalSettings.Instance.UpdateCheck_last = DateTime.Now;
        }
    }
}
